<!DOCTYPE html>
<html>
<head>
    <title>销售结算管理</title>
    <link rel="stylesheet" href="../static/css/ej.css">
    <link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Bootstrap Icons -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css" rel="stylesheet">
    <style>
        .settle-container {
            max-width: 1400px;
            margin: 20px auto;
            padding: 20px;
        }
        .filter-panel {
            background-color: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        .data-table {
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        .table-header {
            background-color: #c0a36c;
            color: white;
            padding: 15px 20px;
        }
        .table-container {
            overflow-x: auto;
        }
        table {
            width: 100%;
            border-collapse: collapse;
        }
        th, td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #eee;
        }
        /* 勾选列 - 缩小 */
        #salesTable th:nth-child(1), 
        #salesTable td:nth-child(1) {
            width: 35px !important;
            min-width: 35px !important;
            max-width: 35px !important;
            text-align: center !important;
            padding: 8px 1px !important;
        }
        
        /* 序号列 - 适当增加宽度 */
        #salesTable th:nth-child(2), 
        #salesTable td:nth-child(2),
        #salesTable .sequence-cell {
            width: 35px ;
            min-width: 35px ;
            max-width: 35px ;
            text-align: center ;
            padding: 8px 3px ;
            font-size: 11px ;
        }
        
        /* 销售时间列 - 调整宽度 */
        th:nth-child(3), td:nth-child(3) {
            width: 80px;
            min-width: 80px;
            max-width: 80px;
            font-size: 11px ;
        }
         /* 库存编号列 - 调整宽度 */
        th:nth-child(4), td:nth-child(4) {
            width: 120px;
            min-width: 120px;
            max-width: 120px;
            text-align: center;
            font-size: 11px ;
        }
        /* 买家姓名列 - 调整宽度 */
        th:nth-child(5), td:nth-child(5) {
            width: 80px;
            min-width: 80px;
            max-width: 80px;
        }
        /* 销售数量列 - 调整宽度 */
        th:nth-child(6), td:nth-child(6) {
            width: 50px;
            min-width: 50px;
            max-width: 50px;
            text-align: center;
        }
        /* 价格相关列 - 调整宽度 */
        th:nth-child(7), td:nth-child(7),
        th:nth-child(8), td:nth-child(8),
        th:nth-child(9), td:nth-child(9),
        th:nth-child(10), td:nth-child(10),
        th:nth-child(11), td:nth-child(11) {
            width: 80px;
            min-width: 80px;
            max-width: 80px;
            text-align: right;
        }
        /* 结算状态列 - 调整宽度 */
        th:nth-child(12), td:nth-child(12) {
            width: 100px;
            min-width: 100px;
            max-width: 100px;
            text-align: center;
        }
        /* 结算时间列 - 调整宽度 */
        th:nth-child(13), td:nth-child(13) {
            width: 100px;
            min-width: 100px;
            max-width: 100px;
            font-size: 11px ;
        }
        /* 结算收款人列 - 调整宽度 */
        th:nth-child(14), td:nth-child(14) {
            width: 100px;
            min-width: 100px;
            max-width: 100px;
        }
        /* 备注列 - 调整宽度 */
        th:nth-child(15), td:nth-child(15) {
            width: 120px;
            min-width: 120px;
            max-width: 120px;
            font-size: 11px ;
        }
        /* 操作列 - 固定宽度 */
        th:nth-child(16), td:nth-child(16) {
            width: 90px;
            min-width: 90px;
            max-width: 90px;
            text-align: center;
        }
        th {
            background-color: #f8f9fa;
            font-weight: 600;
            color: #333;
            font-size: 13px !important;
        }
        tr:hover {
            background-color: #f8f9fa;
        }
        .status-badge {
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 500;
        }
        .status-pending {
            background-color: #fff3cd;
            color: #856404;
        }
        .status-partial {
            background-color: #d1ecf1;
            color: #0c5460;
        }
        .status-completed {
            background-color: #d4edda;
            color: #155724;
        }
        .status-not_necessary {
            background-color: #e2e3e5;
            color: #383d41;
        }
        .loading {
            text-align: center;
            padding: 40px;
            color: #666;
        }
        .error {
            color: #d32f2f;
            padding: 15px;
            background-color: #ffebee;
            border-radius: 4px;
            margin: 10px 0;
        }
        .checkbox-group {
            display: flex;
            gap: 20px;
            flex-wrap: wrap;
        }
        .form-check {
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .form-check-input {
            width: 18px;
            height: 18px;
            margin: 0;
        }
        .form-check-label {
            margin: 0;
            font-weight: 500;
        }
        .action-btn {
            background-color: #c0a36c;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }
        .action-btn:hover {
            background-color: #a88c5a;
        }
        .action-btn.disabled {
            background-color: #cccccc;
            color: #666666;
            cursor: not-allowed;
            opacity: 0.6;
        }
        .action-btn.disabled:hover {
            background-color: #cccccc;
        }
        .price-cell {
            text-align: right;
            font-family: monospace;
        }

        /* 移动版样式 */
        .mobile-cards {
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            overflow: hidden;
            margin-bottom: 20px;
        }
        .mobile-header {
            background-color: #c0a36c;
            color: white;
            padding: 15px 20px;
        }
        .sale-card {
            padding: 15px;
            border-bottom: 2px solid #e0e0e0;
            cursor: pointer;
            margin-bottom: 12px;
            border-radius: 8px;
            background-color: #ffffff;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
        .sale-card:last-child {
            border-bottom: 2px solid #e0e0e0;
            margin-bottom: 0;
        }
        .sale-card:hover {
            background-color: #f5f5f5;
            box-shadow: 0 2px 6px rgba(0,0,0,0.15);
        }
        .sale-card.expanded {
            background-color: #f0f8ff;
            box-shadow: 0 2px 8px rgba(0,0,0,0.2);
        }
        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }
        .card-main-info {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .card-image {
            width: 50px;
            height: 50px;
            object-fit: cover;
            border-radius: 4px;
        }
        .card-basic-info {
            flex: 1;
        }
        .card-stock-id {
            font-weight: 600;
            font-size: 10px; /* 缩小移动版stock_id文字大小 */
            color: #333;
        }
        .card-buyer-name {
            font-size: 14px;
            color: #666;
        }
        .card-status {
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 500;
            min-width: 60px;      /* 设置最小宽度 */
            max-width: 60px;      /* 设置最大宽度，保持固定 */
            text-align: center;   /* 文字居中 */
            white-space: nowrap;  /* 防止文字换行 */
            overflow: hidden;     /* 隐藏溢出内容 */
            text-overflow: ellipsis; /* 超出显示省略号 */
        }
        .card-details {
            display: none;
            margin-top: 10px;
            padding-top: 10px;
            border-top: 1px solid #eee;
        }
        .card-detail-row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 5px;
            font-size: 14px;
        }
        .card-detail-label {
            color: #666;
            min-width: 80px;
        }
        .card-detail-value {
            color: #333;
            text-align: right;
        }
        .card-action {
            margin-top: 10px;
            text-align: center;
        }
        .mobile-action-btn {
            background-color: #c0a36c;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            width: 100%;
        }
        .mobile-action-btn.disabled {
            background-color: #cccccc;
            color: #666666;
            cursor: not-allowed;
            opacity: 0.6;
        }
        .mobile-action-btn.disabled:hover {
            background-color: #cccccc;
        }

        /* 响应式媒体查询 */
        @media (max-width: 768px) {
            .data-table {
                display: none;
            }
            .mobile-cards {
                display: block;
            }
            .settle-container {
                padding: 10px;
            }
            .filter-panel {
                padding: 15px;
            }
            .checkbox-group {
                gap: 10px;
            }
        }
        @media (min-width: 769px) {
            .mobile-cards {
                display: none;
            }
            .data-table {
                display: block;
            }
        }
    </style>
</head>
<body style="background-color:#fffbf6">
    
    <!-- 状态栏 -->
    {% include 'status_bar.html' %}
    
    <!-- 返回主菜单按钮 -->
    <div style="max-width: 1400px; margin: 20px auto 10px auto; padding: 0 20px;">
        <a href="/ej_index" class="btn btn-outline-secondary btn-sm" style="margin-bottom: 10px;">
            <i class="bi bi-arrow-left"></i> 返回主菜单
        </a>
    </div>
    
    <div class="settle-container">
        <h2>销售结算管理</h2>

        <!-- 筛选面板 -->
        <div class="filter-panel">
            <div class="row">
                <div class="col-md-8">
                    <h5>结算状态筛选</h5>
                    <div class="checkbox-group">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="filterPending" checked>
                            <label class="form-check-label" for="filterPending">
                                未结算 (pending)
                            </label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="filterPartial" checked>
                            <label class="form-check-label" for="filterPartial">
                                部分结算 (partial)
                            </label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="filterCompleted" checked>
                            <label class="form-check-label" for="filterCompleted">
                                已结算完毕 (completed)
                            </label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="filterNotNecessary" checked>
                            <label class="form-check-label" for="filterNotNecessary">
                                无需结算 (not_necessary)
                            </label>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div style="display: flex; gap: 10px; align-items: end; height: 100%;">
                        <button class="action-btn" onclick="loadSalesData()">
                            <i class="bi bi-arrow-repeat"></i> 刷新数据
                        </button>
                        <button class="action-btn" id="batchSettleBtn" onclick="handleBatchSettle()" disabled>
                            <i class="bi bi-cash-stack"></i> 一起结算
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <div id="loading" class="loading" style="display: none;">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">加载中...</span>
            </div>
            <p>正在加载销售数据...</p>
        </div>

        <div id="error" class="error" style="display: none;"></div>

        <!-- 数据表格 - PC版 -->
        <div class="data-table">
            <div class="table-header">
                <h5 style="margin: 0;">销售数据列表</h5>
            </div>
            <div class="table-container">
                <table id="salesTable">
                    <thead>
                    <tr>
                        <th>
                            <input type="checkbox" id="selectAll" class="form-check-input">
                        </th>
                        <th>序号</th>
                        <th>销售时间</th>
                        <th>库存编号</th>
                        <th>图片</th>
                        <th>买家姓名</th>
                        <th>销售数量</th>
                        <th>销售价格</th>
                        <th>实际价格</th>
                        <th>总价格</th>
                        <th>结算价格</th>
                        <th>结算状态</th>
                        <th>结算时间</th>
                        <th>结算收款人 </th>
                        <th>备注</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody id="salesTableBody">
                        <!-- 数据将通过JavaScript动态填充 -->
                    </tbody>
                </table>
            </div>
        </div>

        <!-- 移动版卡片容器 -->
        <div id="mobileCards" class="mobile-cards" style="display: none;">
            <div class="mobile-header">
                <h5 style="margin: 0;">销售数据列表</h5>
            </div>
            <div id="mobileCardsBody">
                <!-- 移动版卡片将通过JavaScript动态填充 -->
            </div>
        </div>
    </div>

    <!-- 结算模态框 -->
    <div class="modal fade" id="settleModal" tabindex="-1" aria-labelledby="settleModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="settleModalLabel">销售结算</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="settleForm">
                        <input type="hidden" id="settleSaleId" name="sale_id">
                        
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label">销售ID</label>
                                <input type="text" class="form-control" id="modalSaleId" readonly>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">库存编号</label>
                                <input type="text" class="form-control" id="modalStockId" readonly>
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label">买家姓名</label>
                                <input type="text" class="form-control" id="modalBuyerName" readonly>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">销售数量</label>
                                <input type="text" class="form-control" id="modalSaleQty" readonly>
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label">总价格</label>
                                <input type="text" class="form-control" id="modalTotalPrice" readonly>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">已结算金额</label>
                                <input type="text" class="form-control" id="modalSettledPrice" readonly>
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label required">结算金额</label>
                                <input type="number" step="0.01" class="form-control" id="settleAmount" name="settle_amount" required min="0">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label required"> 收款人</label>
                                <select class="form-control" id="settlePayer" name="settle_payer" required>
                                    <option value="">请选择收款人</option>
                                </select>
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label">结算时间</label>
                                <input type="datetime-local" class="form-control" id="settleDateTime" name="settle_datetime">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">备注</label>
                                <textarea class="form-control" id="settleComment" name="settle_comment" rows="2"></textarea>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="submitSettlement()">确认结算</button>
                </div>
            </div>
        </div>
    </div>

    <script src="../static/js/common.js"></script>
    <script src="../static/js/ejj_functions.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        let salesData = [];
        
        // 检测是否为移动设备
        function isMobileDevice() {
            return window.innerWidth <= 768;
        }

        // 根据设备类型显示正确的视图
        function toggleViewBasedOnDevice() {
            const isMobile = isMobileDevice();
            const pcTable = document.querySelector('.data-table');
            const mobileCards = document.getElementById('mobileCards');
            
            if (isMobile) {
                pcTable.style.display = 'none';
                mobileCards.style.display = 'block';
            } else {
                pcTable.style.display = 'block';
                mobileCards.style.display = 'none';
            }
        }

        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 绑定筛选器改变事件
            document.getElementById('filterPending').addEventListener('change', filterSalesData);
            document.getElementById('filterPartial').addEventListener('change', filterSalesData);
            document.getElementById('filterCompleted').addEventListener('change', filterSalesData);
            document.getElementById('filterNotNecessary').addEventListener('change', filterSalesData);
            
            // 全选/取消全选功能
            document.getElementById('selectAll').addEventListener('change', function() {
                const isChecked = this.checked;
                document.querySelectorAll('.sale-checkbox, .mobile-sale-checkbox').forEach(checkbox => {
                    if (!checkbox.disabled) {
                        checkbox.checked = isChecked;
                    }
                });
                updateBatchSettleButton();
            });
            
            // 监听单个勾选框变化
            document.addEventListener('change', function(e) {
                if (e.target.classList.contains('sale-checkbox') || e.target.classList.contains('mobile-sale-checkbox')) {
                    updateBatchSettleButton();
                }
            });
            
            // 初始显示正确的视图
            toggleViewBasedOnDevice();
            
            // 监听窗口大小变化
            window.addEventListener('resize', toggleViewBasedOnDevice);
            
            // 加载支付人选项
            loadSettlePayers();
            // 加载销售数据
            loadSalesData();
        });

        // 加载支付人选项
        function loadSettlePayers() {
            fetch('/get_ejj_jade_json_config')
                .then(response => response.json())
                .then(data => {
                    if (data.config && data.config.sale_settler) {
                        const payerSelect = document.getElementById('settlePayer');
                        payerSelect.innerHTML = '<option value="">请选择支付人</option>';
                        
                        data.config.sale_settler.forEach(payer => {
                            const option = document.createElement('option');
                            option.value = payer.name;
                            option.textContent = payer.name;
                            payerSelect.appendChild(option);
                        });
                    }
                })
                .catch(error => {
                    console.error('加载支付人选项失败:', error);
                });
        }

        // 加载销售数据
        function loadSalesData() {
            const loading = document.getElementById('loading');
            const error = document.getElementById('error');
            
            loading.style.display = 'block';
            error.style.display = 'none';

            fetch('/get_sale_settle_data')
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.json();
                })
                .then(data => {
                    loading.style.display = 'none';
                    if (data.success && data.data) {
                        salesData = data.data;
                        filterSalesData();
                    } else {
                        throw new Error(data.message || '数据格式错误');
                    }
                })
                .catch(error => {
                    loading.style.display = 'none';
                    error.style.display = 'block';
                    error.textContent = '加载销售数据失败: ' + error.message;
                });
        }

        // 根据筛选条件过滤数据
        function filterSalesData() {
            const showPending = document.getElementById('filterPending').checked;
            const showPartial = document.getElementById('filterPartial').checked;
            const showCompleted = document.getElementById('filterCompleted').checked;
            const showNotNecessary = document.getElementById('filterNotNecessary').checked;

            const filteredData = salesData.filter(sale => {
                const status = sale.settlement_status;
                return (showPending && status === 'pending') ||
                       (showPartial && status === 'partial') ||
                       (showCompleted && status === 'completed') ||
                       (showNotNecessary && status === 'not_necessary');
            });

            renderSalesTable(filteredData);
            renderMobileCards(filteredData);
        }

        // 渲染销售数据表格
        function renderSalesTable(data) {
            const tableBody = document.getElementById('salesTableBody');
            tableBody.innerHTML = '';

            if (data.length === 0) {
                tableBody.innerHTML = `
                    <tr>
                        <td colspan="13" style="text-align: center; padding: 20px; color: #666;">
                            没有找到匹配的销售数据
                        </td>
                    </tr>
                `;
                return;
            }

            data.forEach((sale, index) => {
                const row = document.createElement('tr');
                
                // 根据结算状态设置CSS类
                let statusClass = '';
                let statusText = '';
                switch(sale.settlement_status) {
                    case 'pending':
                        statusClass = 'status-pending';
                        statusText = '未结算';
                        break;
                    case 'partial':
                        statusClass = 'status-partial';
                        statusText = '部分结算';
                        break;
                    case 'completed':
                        statusClass = 'status-completed';
                        statusText = '已结算';
                        break;
                    case 'not_necessary':
                        statusClass = 'status-not_necessary';
                        statusText = '无需结算';
                        break;
                    default:
                        statusClass = '';
                        statusText = sale.settlement_status;
                }

                // 检查是否应该禁用结算按钮
                const isDisabled = sale.settlement_status === 'completed' || sale.settlement_status === 'not_necessary';
                const buttonClass = isDisabled ? 'action-btn disabled' : 'action-btn';
                const buttonDisabled = isDisabled ? 'disabled' : '';
                const buttonTitle = isDisabled ? '该记录已结算完毕或无需结算' : '点击进行结算';
                
                // 生成产品图片HTML
                const productImageHtml = sale.product_id ? 
                    `<img src="/serve_jade_image?product_id=${sale.product_id}" 
                          alt="${sale.product_id}" 
                          style="width: 50px; height: 50px; object-fit: cover; border-radius: 4px; cursor: pointer;"
                          onerror="this.src='/static/images/default_cover.jpg'"
                          onclick="showJadeImages('${sale.product_id}')"
                          title="点击查看产品图片">` : 
                    '<span style="color: #999;">无图片</span>';
                
                row.innerHTML = `
                    <td>
                        <input type="checkbox" class="form-check-input sale-checkbox" 
                               value="${sale.id}" 
                               ${isDisabled ? 'disabled' : ''}>
                    </td>
                    <td class="sequence-cell">${index + 1}</td>
                    <td>${formatDateTime(sale.sale_datetime)}</td>
                    <td>${sale.stock_id || ''}</td>
                    <td style="text-align: center;">${productImageHtml}</td>
                    <td>${sale.buyer_name || ''}</td>
                    <td class="price-cell">${formatInteger(sale.sale_qty)}</td>
                    <td class="price-cell">¥${formatNumber(sale.sale_price)}</td>
                    <td class="price-cell">¥${formatNumber(sale.sale_real_price)}</td>
                    <td class="price-cell">¥${formatNumber(sale.sale_total_price)}</td>
                    <td class="price-cell">¥${formatNumber(sale.settled_price)}</td>
                    <td><span class="status-badge ${statusClass}">${statusText}</span></td>
                    <td>${formatDateTime(sale.settled_datetime)}</td>
                    <td>${sale.settle_payer || ''}</td>
                    <td title="${sale.comment || ''}">${truncateText(sale.comment, 30)}</td>
                    <td>
                        <button class="${buttonClass}" onclick="${isDisabled ? '' : `showSettleModal('${sale.id}')`}" ${buttonDisabled} title="${buttonTitle}">
                            <i class="bi bi-cash-coin"></i> 结算
                        </button>
                    </td>
                `;
                
                tableBody.appendChild(row);
            });
        }

        // 渲染移动版卡片
        function renderMobileCards(data) {
            const cardsBody = document.getElementById('mobileCardsBody');
            cardsBody.innerHTML = '';

            if (data.length === 0) {
                cardsBody.innerHTML = `
                    <div class="sale-card">
                        <div style="text-align: center; padding: 20px; color: #666;">
                            没有找到匹配的销售数据
                        </div>
                    </div>
                `;
                return;
            }

            data.forEach((sale, index) => {
                // 根据结算状态设置CSS类
                let statusClass = '';
                let statusText = '';
                switch(sale.settlement_status) {
                    case 'pending':
                        statusClass = 'status-pending';
                        statusText = '未结算';
                        break;
                    case 'partial':
                        statusClass = 'status-partial';
                        statusText = '部分结算';
                        break;
                    case 'completed':
                        statusClass = 'status-completed';
                        statusText = '已结算';
                        break;
                    case 'not_necessary':
                        statusClass = 'status-not_necessary';
                        statusText = '无需结算';
                        break;
                    default:
                        statusClass = '';
                        statusText = sale.settlement_status;
                }

                // 检查是否应该禁用结算按钮
                const isDisabled = sale.settlement_status === 'completed' || sale.settlement_status === 'not_necessary';
                const buttonClass = isDisabled ? 'mobile-action-btn disabled' : 'mobile-action-btn';
                const buttonDisabled = isDisabled ? 'disabled' : '';
                const buttonTitle = isDisabled ? '该记录已结算完毕或无需结算' : '点击进行结算';
                
                // 生成产品图片HTML
                const productImageHtml = sale.product_id ? 
                    `<img src="/serve_jade_image?product_id=${sale.product_id}" 
                          alt="${sale.product_id}" 
                          class="card-image"
                          onerror="this.src='/static/images/default_cover.jpg'"
                          onclick="showJadeImages('${sale.product_id}')"
                          title="点击查看产品图片">` : 
                    '<span style="color: #999; font-size: 12px;">无图片</span>';

                const card = document.createElement('div');
                card.className = 'sale-card';
                card.innerHTML = `
                    <div class="card-header">
                        <div class="card-main-info">
                            <input type="checkbox" class="form-check-input mobile-sale-checkbox" 
                                   value="${sale.id}" 
                                   ${isDisabled ? 'disabled' : ''}
                                   style="margin-right: 10px;">
                            ${productImageHtml}
                            <div class="card-basic-info">
                                <div class="card-stock-id">${sale.stock_id || '无编号'}</div>
                                <div class="card-buyer-name">${sale.buyer_name || '无买家'}</div>
                            </div>
                        </div>
                        <span class="card-status ${statusClass}">${statusText}</span>
                    </div>
                    
                    <div class="card-details">
                        <div class="card-detail-row">
                            <span class="card-detail-label">销售时间:</span>
                            <span class="card-detail-value">${formatDateTime(sale.sale_datetime)}</span>
                        </div>
                        <div class="card-detail-row">
                            <span class="card-detail-label">销售数量:</span>
                            <span class="card-detail-value">${formatInteger(sale.sale_qty)}</span>
                        </div>
                        <div class="card-detail-row">
                            <span class="card-detail-label">销售价格:</span>
                            <span class="card-detail-value">¥${formatNumber(sale.sale_price)}</span>
                        </div>
                        <div class="card-detail-row">
                            <span class="card-detail-label">实际价格:</span>
                            <span class="card-detail-value">¥${formatNumber(sale.sale_real_price)}</span>
                        </div>
                        <div class="card-detail-row">
                            <span class="card-detail-label">总价格:</span>
                            <span class="card-detail-value">¥${formatNumber(sale.sale_total_price)}</span>
                        </div>
                        <div class="card-detail-row">
                            <span class="card-detail-label">已结算:</span>
                            <span class="card-detail-value">¥${formatNumber(sale.settled_price)}</span>
                        </div>
                        ${sale.settled_datetime ? `
                        <div class="card-detail-row">
                            <span class="card-detail-label">结算时间:</span>
                            <span class="card-detail-value">${formatDateTime(sale.settled_datetime)}</span>
                        </div>
                        ` : ''}
                        ${sale.settle_payer ? `
                        <div class="card-detail-row">
                            <span class="card-detail-label">收款人:</span>
                            <span class="card-detail-value">${sale.settle_payer}</span>
                        </div>
                        ` : ''}
                        ${sale.comment ? `
                        <div class="card-detail-row">
                            <span class="card-detail-label">备注:</span>
                            <span class="card-detail-value">${truncateText(sale.comment, 50)}</span>
                        </div>
                        ` : ''}
                    </div>
                    
                    <div class="card-action">
                        <button class="${buttonClass}" onclick="${isDisabled ? '' : `showSettleModal('${sale.id}')`}" ${buttonDisabled} title="${buttonTitle}">
                            <i class="bi bi-cash-coin"></i> 结算
                        </button>
                    </div>
                `;
                
                // 添加点击展开/收起功能
                card.addEventListener('click', function(e) {
                    // 防止点击按钮时触发卡片展开
                    if (e.target.tagName === 'BUTTON' || e.target.tagName === 'IMG') {
                        return;
                    }
                    
                    const details = this.querySelector('.card-details');
                    const isExpanded = details.style.display === 'block';
                    
                    if (isExpanded) {
                        details.style.display = 'none';
                        this.classList.remove('expanded');
                    } else {
                        details.style.display = 'block';
                        this.classList.add('expanded');
                    }
                });
                
                cardsBody.appendChild(card);
            });
        }

        // 格式化日期时间
        function formatDateTime(dateTimeStr) {
            if (!dateTimeStr) return '';
            const date = new Date(dateTimeStr);
            return date.toLocaleString('zh-CN');
        }

        // 格式化数字（保留2位小数）
        function formatNumber(num) {
            if (num === null || num === undefined) return '0.00';
            return parseFloat(num).toFixed(2);
        }

        // 格式化整数（去掉小数部分）
        function formatInteger(num) {
            if (num === null || num === undefined) return '0';
            return parseInt(num).toString();
        }

        // 截断文本
        function truncateText(text, maxLength) {
            if (!text) return '';
            if (text.length <= maxLength) return text;
            return text.substring(0, maxLength) + '...';
        }

        // 显示结算模态框
        function showSettleModal(saleId) {
            // 查找对应的销售数据
            const sale = salesData.find(s => s.id == saleId);
            if (!sale) {
                alert('未找到对应的销售数据');
                return;
            }

            // 填充模态框数据
            document.getElementById('settleSaleId').value = sale.id;
            document.getElementById('modalSaleId').value = sale.id;
            document.getElementById('modalStockId').value = sale.stock_id || '';
            document.getElementById('modalBuyerName').value = sale.buyer_name || '';
            document.getElementById('modalSaleQty').value = formatInteger(sale.sale_qty);
            document.getElementById('modalTotalPrice').value = '¥' + formatNumber(sale.sale_total_price);
            document.getElementById('modalSettledPrice').value = '¥' + formatNumber(sale.settled_price || 0);
            
            // 计算并设置结算金额（总价格 - 已结算金额）
            const totalPrice = parseFloat(sale.sale_total_price || 0);
            const settledPrice = parseFloat(sale.settled_price || 0);
            const settleAmount = totalPrice - settledPrice;
            document.getElementById('settleAmount').value = settleAmount > 0 ? settleAmount.toFixed(2) : '';
            
            // 设置当前时间为默认结算时间
            const now = new Date();
            const localDateTime = now.toISOString().slice(0, 16);
            document.getElementById('settleDateTime').value = localDateTime;
            
            // 清空其他表单字段
            document.getElementById('settlePayer').value = '';
            document.getElementById('settleComment').value = '';

            // 显示模态框
            const modal = new bootstrap.Modal(document.getElementById('settleModal'));
            modal.show();
        }

        // 提交结算信息
        function submitSettlement() {
            const formData = new FormData(document.getElementById('settleForm'));
            const data = Object.fromEntries(formData.entries());
            
            // 验证必填字段
            if (!data.settle_amount || !data.settle_payer) {
                alert('请填写结算金额和支付人');
                return;
            }

            // 添加时间戳
            data.updated_at = new Date().toISOString();
            
            // 发送结算请求
            fetch('/update_sale_settlement', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data)
            })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    alert('结算成功！');
                    // 关闭模态框
                    const modal = bootstrap.Modal.getInstance(document.getElementById('settleModal'));
                    modal.hide();
                    // 重新加载数据
                    loadSalesData();
                } else {
                    alert('结算失败: ' + result.message);
                }
            })
            .catch(error => {
                alert('结算请求失败: ' + error.message);
            });
        }


        // 更新批量结算按钮状态
        function updateBatchSettleButton() {
            const batchBtn = document.getElementById('batchSettleBtn');
            const hasSelected = document.querySelectorAll('.sale-checkbox:checked, .mobile-sale-checkbox:checked').length > 0;
            
            if (hasSelected) {
                batchBtn.disabled = false;
                batchBtn.classList.remove('disabled');
            } else {
                batchBtn.disabled = true;
                batchBtn.classList.add('disabled');
            }
        }

        // 处理批量结算
        function handleBatchSettle() {
            const selectedCheckboxes = document.querySelectorAll('.sale-checkbox:checked, .mobile-sale-checkbox:checked');
            
            if (selectedCheckboxes.length === 0) {
                alert('请选择要结算的销售记录');
                return;
            }

            const selectedSaleIds = Array.from(selectedCheckboxes).map(checkbox => checkbox.value);
            
            // 获取当前时间
            const now = new Date();
            const settleDateTime = now.toISOString().slice(0, 16);
            
            // 创建批量结算模态框
            const batchModalHtml = `
                <div class="modal fade" id="batchSettleModal" tabindex="-1" aria-labelledby="batchSettleModalLabel" aria-hidden="true">
                    <div class="modal-dialog">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title" id="batchSettleModalLabel">批量结算</h5>
                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                            </div>
                            <div class="modal-body">
                                <p>您选择了 <strong>${selectedSaleIds.length}</strong> 条销售记录进行批量结算。</p>
                                <div class="mb-3">
                                    <label class="form-label required">收款人</label>
                                    <select class="form-control" id="batchSettlePayer" required>
                                        <option value="">请选择收款人</option>
                                    </select>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">结算时间</label>
                                    <input type="datetime-local" class="form-control" id="batchSettleDateTime" value="${settleDateTime}">
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">备注</label>
                                    <textarea class="form-control" id="batchSettleComment" rows="2"></textarea>
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                                <button type="button" class="btn btn-primary" onclick="submitBatchSettlement()">确认批量结算</button>
                            </div>
                        </div>
                    </div>
                </div>
            `;
            
            // 添加模态框到页面
            if (!document.getElementById('batchSettleModal')) {
                document.body.insertAdjacentHTML('beforeend', batchModalHtml);
            }
            
            // 填充收款人选项
            const payerSelect = document.getElementById('batchSettlePayer');
            payerSelect.innerHTML = '<option value="">请选择收款人</option>';
            document.getElementById('settlePayer').querySelectorAll('option').forEach(option => {
                if (option.value) {
                    payerSelect.appendChild(option.cloneNode(true));
                }
            });
            
            // 显示模态框
            const modal = new bootstrap.Modal(document.getElementById('batchSettleModal'));
            modal.show();
            
            // 存储选中的销售ID
            window.selectedBatchSaleIds = selectedSaleIds;
        }

        // 提交批量结算
        function submitBatchSettlement() {
            const payer = document.getElementById('batchSettlePayer').value;
            const settleDateTime = document.getElementById('batchSettleDateTime').value;
            const comment = document.getElementById('batchSettleComment').value;
            
            if (!payer) {
                alert('请选择收款人');
                return;
            }

            // 收集每个销售记录的结算金额（总价格）
            const saleSettlements = [];
            const selectedCheckboxes = document.querySelectorAll('.sale-checkbox:checked, .mobile-sale-checkbox:checked');
            
            selectedCheckboxes.forEach(checkbox => {
                const saleId = checkbox.value;
                // 查找对应的销售记录数据
                const sale = salesData.find(s => s.id == saleId);
                if (sale) {
                    // 计算未支付金额（总价格 - 已结算金额）
                    const totalPrice = parseFloat(sale.sale_total_price || 0);
                    const settledPrice = parseFloat(sale.settled_price || 0);
                    const settleAmount = totalPrice - settledPrice;
                    
                    if (settleAmount > 0) {
                        saleSettlements.push({
                            sale_id: saleId,
                            settle_amount: settleAmount
                        });
                    }
                }
            });

            if (saleSettlements.length === 0) {
                alert('选中的销售记录没有需要结算的金额');
                return;
            }

            const batchData = {
                sale_settlements: saleSettlements,
                settle_payer: payer,
                settle_datetime: settleDateTime,
                settle_comment: comment,
                updated_at: new Date().toISOString()
            };

            console.log('批量结算数据:', batchData);

            // 发送批量结算请求
            fetch('/batch_update_sale_settlement', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(batchData)
            })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    alert(`批量结算成功！共处理了 ${result.settled_count} 条记录`);
                    // 关闭模态框
                    const modal = bootstrap.Modal.getInstance(document.getElementById('batchSettleModal'));
                    modal.hide();
                    // 重新加载数据
                    loadSalesData();
                } else {
                    alert('批量结算失败: ' + result.message);
                }
            })
            .catch(error => {
                alert('批量结算请求失败: ' + error.message);
            });
        }

        // 初始化页面
        loadSalesData();

    </script>
</body>
</html>
